package com.yumeng.framework.auth.shiro.filter;

import com.yumeng.framework.auth.exception.ShiroAuthException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.CollectionUtils;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.http.HttpStatus;

import java.io.IOException;
import java.util.Set;

/**
 *
 * 逻辑同org.apache.shiro.web.filter.authz.RolesAuthorizationFilter 只是为了做一些测试
 *
 * 无法再现.FILTERED异常，因为二次访问的/error 不会进入该过滤器，只能在最终过滤器类似（jwtFilter）中研究这个问题
 *
 * @author wxd
 * @date 2022/4/24 9:03
 */
@Slf4j
public class MyRolesAuthorizationFilter extends AuthorizationFilter {

    private static final String FILTER_NAME = "myRoles";

    public static String getFilterName(){
        return FILTER_NAME;
    }

    @Override
    protected void postHandle(ServletRequest request, ServletResponse response){
        request.setAttribute("myRolesAuthorizationFilter.FILTERED", true);
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        Boolean afterFiltered = (Boolean)(request.getAttribute("myRolesAuthorizationFilter.FILTERED"));
        if( BooleanUtils.isTrue(afterFiltered)){
            throw new ShiroAuthException(String.format("MyRolesAuthorizationFilter-已过滤标志:%s", WebUtils.toHttp(request).getRequestURI()));
        }


        Subject subject = getSubject(request, response);
        String[] rolesArray = (String[]) mappedValue;

        if (rolesArray == null || rolesArray.length == 0) {
            //no roles specified, so nothing to check - allow access.
            return true;
        }

        Set<String> roles = CollectionUtils.asSet(rolesArray);
        boolean b = subject.hasAllRoles(roles);
        return b;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        HttpServletResponse httpResponse = WebUtils.toHttp(response);
        httpResponse.setCharacterEncoding("UTF-8");
        httpResponse.setContentType("application/json;charset=utf-8");
        httpResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
        return false;
    }
}
